using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Read.Api.Application.Command.HospitalExpense;
using SmartHealthcare.Read.Api.DTo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace SmartHealthcare.Read.Api.Application.Handler.HospitalExpense
{
    /// <summary>
    /// 获取住院费用记录列表处理器
    /// </summary>
    public class GetHospitalExpensesHandler : IRequestHandler<GetHospitalExpensesCommand, APIResult<List<HospitalExpenseDto>>>
    {
        private readonly IBaseRepository<HospitalExpenseModel> expenseRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetHospitalExpensesHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="expenseRepository">住院费用记录仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetHospitalExpensesHandler(
            IBaseRepository<HospitalExpenseModel> expenseRepository,
            IMapper mapper,
            ILogger<GetHospitalExpensesHandler> logger)
        {
            this.expenseRepository = expenseRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 处理获取住院费用记录列表请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>住院费用记录列表</returns>
        public Task<APIResult<List<HospitalExpenseDto>>> Handle(GetHospitalExpensesCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<HospitalExpenseDto>> result = new APIResult<List<HospitalExpenseDto>>();

            try
            {
                logger.LogInformation($"开始查询住院费用记录，查询条件：InpatientRegistryId={request.InpatientRegistryId}, " +
                    $"MedicalCard={request.MedicalCard}, PatientName={request.PatientName}, " +
                    $"StartTime={request.StartTime}, EndTime={request.EndTime}, ItemType={request.ItemType}");

                // 获取所有未删除的住院费用记录
                var query = expenseRepository.GetALL().Where(x => !x.IsDeleted);

                // 根据住院登记ID筛选
                if (request.InpatientRegistryId.HasValue)
                {
                    query = query.Where(x => x.InpatientRegistryId == request.InpatientRegistryId.Value);
                    logger.LogInformation($"添加住院登记ID筛选条件：{request.InpatientRegistryId.Value}");
                }

                // 根据病人卡号筛选
                if (!string.IsNullOrEmpty(request.MedicalCard))
                {
                    query = query.Where(x => x.MedicalCard == request.MedicalCard);
                    logger.LogInformation($"添加病人卡号筛选条件：{request.MedicalCard}");
                }

                // 根据患者姓名筛选
                if (!string.IsNullOrEmpty(request.PatientName))
                {
                    query = query.Where(x => x.PatientName.Contains(request.PatientName));
                    logger.LogInformation($"添加患者姓名筛选条件：{request.PatientName}");
                }

                // 根据时间范围筛选
                if (request.StartTime.HasValue)
                {
                    query = query.Where(x => x.ExpenseTime >= request.StartTime.Value);
                    logger.LogInformation($"添加开始时间筛选条件：{request.StartTime.Value}");
                }

                if (request.EndTime.HasValue)
                {
                    query = query.Where(x => x.ExpenseTime <= request.EndTime.Value);
                    logger.LogInformation($"添加结束时间筛选条件：{request.EndTime.Value}");
                }

                // 根据项目类型筛选
                if (!string.IsNullOrEmpty(request.ItemType))
                {
                    query = query.Where(x => x.ItemType == request.ItemType);
                    logger.LogInformation($"添加项目类型筛选条件：{request.ItemType}");
                }

                // 按记账时间降序排序（最新的记录在前）
                query = query.OrderByDescending(x => x.ExpenseTime);

                // 执行查询并转换为DTO
                var expenses = query.ToList();
                var expenseDtos = mapper.Map<List<HospitalExpenseDto>>(expenses);

                logger.LogInformation($"查询结果：共找到{expenseDtos.Count}条住院费用记录");

                result.Data = expenseDtos;
                result.Code = APIEnums.Success;
                result.Msg = "查询住院费用记录成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "查询住院费用记录时发生异常");
                result.Code = APIEnums.Fail;
                result.Msg = $"查询住院费用记录失败：{ex.Message}";
            }

            return Task.FromResult(result);
        }
    }
} 